<?php

class MySql {

	var $linkID; //用来保存连接ID
	var $queryID; //用来保存查询ID
	var $persist; //是否持久连接数据库
	var $errno; //mysql出错代号
	var $error; //mysql出错信息
	var $record = array(); //一条记录数组
	var $fetchMode = MYSQL_ASSOC; //取记录时的模式
	var $queryTimes = 0; //保存查询的次数
	
	function MySql ($dbhost, $dbuser, $dbpwd, $dbName) {
		if (empty($dbhost) || empty($dbuser) || empty($dbName)){
			$this->halt("数据库主机地址,用户名或数据库名称不完全,请检查!");
		}
		$this->persist = false;
		$this->connect($dbhost, $dbuser, $dbpwd, $dbName);
		mysql_query("SET NAMES 'utf8'");
	} 


	//连接数据库	
	function connect($dbhost, $dbuser, $dbpwd, $dbName) {
		if ($this->persist == true)
			$this->linkID = mysql_pconnect($dbhost, $dbuser, $dbpwd);
		else
			$this->linkID = mysql_connect($dbhost, $dbuser, $dbpwd); 
		if (!$this->linkID) {
			$this->halt();
		} 
		if (!mysql_select_db($dbName, $this->linkID)) {
			$this->halt();
		} 
		return $this->linkID;
	} 

	//关闭数据库连接
	function disconnect() {
		$ret = @mysql_close($this->linkID);
		$this->linkID = null;
		return $ret;
	}

	function writeLog($sql,$file) {	
		$log_file = PUBLIC_PATH.'log/db/'. date("Y-m-d") . ".log";
		$log_msg = "[" . date("Y-m-d H:i:s") . "] - " . $file . ": " . $sql . " ";
		error_log($log_msg,3,$log_file);
	}

	//数据查询	 
	function query($sql) {
		$this->queryTimes++;
		$this->queryID = mysql_query($sql, $this->linkID);
		if (!$this->queryID) {
			$this->halt($sql);
		} 
		return $this->queryID;
	}

	function getRow($table,$field = '*',$where = ''){		
		$sql = "SELECT $field FROM $table";
		$sql .= trim($where) != '' ? " WHERE $where " : $where;
		$this->query($sql);
		return $this->fetchRow();	
	}

	function getAll($table, $field = '*',$where = '',$order = '',$limit = '') {
		$sql = "SELECT $field FROM $table";
		$sql .= trim($where) != '' ? " WHERE $where " : '';
		$sql .= trim($order) != '' ? " ORDER BY $order " : '';
		$sql .= trim($limit) != '' ? " LIMIT $limit" : '';
		//de($sql);
		$this->query($sql);
		return $this->fetchAll();
	}
	
	//$param['field'] $param['table'] $param['where'] $param['order'] $param['page'] $param['rows']
	function getList($param) {
		$sql = "SELECT {$param['field']} FROM {$param['table']} ";
		if (!empty($param['where'])) {
			$sql .= "WHERE {$param['where']} ";
		} 
		if (!empty($param['order'])) {
			$sql .= " ORDER BY {$param['order']} ";
		} 
		if (!empty($param['page']) && !empty($param['rows'])) {
			$start = ($param['page'] - 1) * $param['rows'];
			$sql .= "LIMIT " . $start . ", " . $param['rows'];
		}
		//de($sql);
		$this->query($sql);
		return $this->fetchAll();
	}

	function getTotal($param) {
		$sql = "SELECT count(*) AS total FROM {$param['table']} ";
		if (!empty($param['where'])) {
			$sql .= "WHERE {$param['where']} ";
		} 
		if (!empty($param['order'])) {
			$sql .= " ORDER BY {$param['order']}  ";
		}
		$this->query($sql);
		$this->fetchRow();
		return $this->getValue("total");
	}

	/**
	 * 获取指定各种条件的记录
	 * @param bool $single 是否只是取单条记录(是调用getRow还是getAll,默认是false,即调用getAll)
	 */
	function getRecord($table, $field = '*', $where = '', $order = '', $limit = '') {
		$sql = "SELECT $field FROM $table";
		$sql .= trim($where) != '' ? " WHERE $where " : $where;
		$sql .= trim($order) != '' ? " ORDER BY '$order' " : $order;
		$sql .= trim($limit) != '' ? " LIMIT $limit" : $limit;
		$this->query($sql);
		return $this->fetchAll();
	} 

	/**
	 * 获取指定条数的记录
	 * 
	 * @param string $table 表名
	 * @param int $start_pos 开始记录
	 * @param int $offset 偏移量
	 * @param string $field 字段名
	 * @param string $where 条件(获取记录的条件语句,不包括WHERE,默认为空)
	 * @param string $order 排序(按照什么字段排序,不包括ORDER BY,默认为空)
	 * @return 成功返回包含记录的二维数组,失败返回false
	 */
	function getLimitRecord($table, $start_pos, $offset, $field = '*', $where = '', $oder = '') {
		$sql = "SELECT $field FROM $table";
		$sql .= trim($where) != '' ? " WHERE $where " : $where;
		$sql .= trim($order) != '' ? " ORDER BY $order" : $order;
		$sql .= "LIMIT $start_pos,$offset";
		return $this->fetchAll($sql);
	}

	/**
	 * 获取排序记录
	 * 
	 * @param string $table 表名
	 * @param string $order_field 需要排序的字段(比如id)
	 * @param string $order_method 排序的方式(1为顺序, 2为逆序, 默认是1)
	 * @param string $field 需要提取的字段(默认是*,就是所有字段)
	 * @param string $where 条件(获取记录的条件语句,不包括WHERE,默认为空)
	 * @param string $limit 限制记录(需要提取多少记录,不包括LIMIT,默认为空)
	 * @return 成功返回记录的二维数组,失败返回false
	 */
	function getOrderRecord($table, $order_field, $order_method = 1, $field = '*', $where = '', $limit = '') {
		// $order_method的值为1则为顺序, $order_method值为2则2则是逆序排列
		$sql = "SELECT $field FROM $table";
		$sql .= trim($where) != '' ? " WHERE $where " : $where;
		$sql .= " ORDER BY $order_field " . ($order_method == 1 ? "ASC" : "DESC");
		$sql .= trim($limit) != '' ? " LIMIT $limit" : $limit;
		return $this->fetchAll($sql);
	} 

	/**
     * 分页查询(限制查询的记录条数)
     *
     * @param string $sql 需要查询的SQL语句
     * @param int $start_pos 开始记录的条数
     * @param int $offset 每次的偏移量,需要获取多少条
     * @return 成功返回获取结果记录的二维数组,失败返回false
     */
    function limitQuery($sql, $start_pos, $offset){
        $start_pos = intval($start_pos);
        $offset = intval($offset);
        $sql = $sql . " LIMIT $start_pos,$offset ";
        return $this->getAll($sql);
    }

	
	/**
     * 自动执行操作(针对Insert/Update操作)
     *
     * @param string $table 表名
     * @param array $field_array 字段数组(数组中的键相当于字段名,数组值相当于值, 类似 array( 'id' => 100, 'user' => 'heiyeluren')
     * @param int $mode 执行操作的模式 (是插入还是更新操作, 1是插入操作Insert, 2是更新操作Update)
     * @param string $where 如果是更新操作,可以添加WHERE的条件
     * @return bool 执行成功返回true, 失败返回false
     */
    function autoExecute($table, $field_array, $mode, $where=''){
        if ($table=='' || !is_array($field_array) || empty($field_array)){
            return false;
        }
        //$mode为1是插入操作(Insert), $mode为2是更新操作
        if ($mode == 1){
            $sql = "INSERT INTO $table SET ";
        }else{
            $sql = "UPDATE $table SET ";
        }
        foreach ($field_array as $key => $value){
            $sql .= "$key='$value',";
        }
        $sql = rtrim($sql, ',');
        if ($mode==2 && $where!=''){
            $sql .= "WHERE $where";
        }
        return $this->query($sql);
    }

	//$field_array 字段数组(数组中的键相当于字段名,数组值相当于值, 类似 array( 'id' => 100, 'user' => 'adminpub')	

	//执行Insert操作
	function add ($table, $field_array) {
		if ($table == '' || !is_array($field_array) || empty($field_array)) {
			return false;
		}		
		$sql = "INSERT INTO $table SET ";		
		foreach ($field_array as $key => $value) {
			$sql .= "$key='$value',";
		} 
		$sql = rtrim($sql, ',');
		$this->query($sql);
		return $this->insertID();
	}
	
	function update ($table, $field_array,$where = '') {		
		$sql = "UPDATE $table SET ";		
		foreach ($field_array as $key => $value) {
			$sql .= "$key='$value',";
		} 
		$sql = rtrim($sql, ',');
		if ($where != '') {
			$sql .= "WHERE $where";
		}
		$this->query($sql);
		return $this->affectedRows();
	} 

	function delete ($table,$where = '') {		
		$sql = "DELETE FROM $table ";
		if ($where != '') {
			$sql .= "WHERE $where ";
		}
		$this->query($sql);
		return $this->affectedRows();
	}
	
	//取出一条记录
	function fetchRow() {
		$this->record = mysql_fetch_array($this->queryID, $this->fetchMode);
		return $this->record;
	}

	//取出所有记录
	function fetchAll() {
		$arr = array();
		while ($this->record = mysql_fetch_array($this->queryID, $this->fetchMode)) {
			$arr[] = $this->record;
		} 
		mysql_free_result($this->queryID);
		return $arr;
	}

	//返回记录中指定字段的数据 @param  $field 字段名或字段索引
	function getValue($field) {
		return $this->record[$field];
	}

	//返回影响的记录数
	function affectedRows() {
		return mysql_affected_rows($this->linkID);
	} 

	//返回查询记录的总数	
	function recordCount() {
		return mysql_num_rows($this->queryID);
	} 

	//返回查询的次数	
	function getQueryTimes() {
		return $this->queryTimes;
	}

	//返回最后一次插入的自增ID	
	function insertID() {
		return mysql_insert_id();
	}

	function halt($sql) {
		$this->writeLog($sql, __FILE__);        
		$this->errno = mysql_errno();
		$this->error = mysql_error();
		$msg = '错误代码: '.$this->errno."<br>错误原因: " . $this->error . "<br>错误语句: " . $sql . "<br>";
		de($msg);
		exit();
	}
} 

?>
